<%-- 
    Document   : uploadimage
    Created on : Dec 6, 2011, 12:50:58 PM
    Author     : kydrenw
--%>

<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="java.io.File,java.io.IOException,java.io.PrintWriter"%>
<%@page import="java.util.Iterator,java.util.List"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.FileUploadException"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.io.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
    File tmpDir = new File("D:\\");
    if (!tmpDir.isDirectory()) {
        throw new ServletException("tmpDir is not a directory");
    }
    String realPath = getServletContext().getRealPath("/product");
    File destinationDir = new File(realPath);
    if (!destinationDir.isDirectory()) {
        throw new ServletException("destinationDir is not a directory");
    }
    //-----------------------------------------------------
    response.setContentType("text/plain");
    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();

    //Set the size threshold, above which content will be stored on disk.     
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB

    //Set the temporary directory to store the uploaded files of size above threshold.     
    fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List items = uploadHandler.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (!item.isFormField()) {
                File file = new File(destinationDir, item.getName());
                item.write(file);
            }
            //out.close();
                          
            response.sendRedirect("sanpham.htm?action=them&image="+item.getName());
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }
%>